<template>
  <div class="workorder-dispatch-container">
    <el-card>
      <h2>工单派发</h2>

      <!-- 工单列表 -->
      <el-table
        :data="dispatchOrderList"
        border
        stripe
        v-loading="isLoading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="_id" label="工单编号" width="180" />
        <el-table-column prop="customer_name" label="客户姓名" width="120" />
        <el-table-column prop="customer_phone" label="联系电话" width="150" />
        <el-table-column prop="user_claim" label="问题描述" min-width="200" />
        <el-table-column prop="status" label="当前状态" width="120" />

        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleDispatch(scope.row)"
              :disabled="scope.row.status !== '待分派维修员'"
            >
              分派维修员
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分派维修员模态框 -->
      <el-dialog
        v-model="showDispatchDialog"
        title="选择维修员"
        width="30%"
        :before-close="handleDialogClose"
      >
        <el-form :model="dispatchForm" label-width="80px">
          <el-form-item label="维修员">
            <el-select
              v-model="dispatchForm.repairmanId"
              placeholder="请选择维修员"
              :disabled="isDispatchLoading"
            >
              <el-option
                v-for="repairman in repairmanList"
                :key="repairman._id"
                :label="repairman.name"
                :value="repairman._id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showDispatchDialog = false" :disabled="isDispatchLoading"
              >取消</el-button
            >
            <el-button
              type="primary"
              @click="confirmDispatch"
              :loading="isDispatchLoading"
              :disabled="!dispatchForm.repairmanId || isDispatchLoading"
            >
              确认分派
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getWorkOrdersByStatus } from '@/api/workOrder' // 从workOrder.js获取工单列表接口
import { getRepairmen } from '@/api/user' // 从user.js获取维修员列表接口
import { assignRepairmanByStation } from '@/api/workOrder' // 从workOrder.js获取分派接口
import { ElMessage } from 'element-plus'

// 状态管理
const dispatchOrderList = ref([]) // 待分派工单列表
const repairmanList = ref([]) // 维修员列表
const isLoading = ref(false) // 工单列表加载状态
const showDispatchDialog = ref(false) // 分派模态框显示状态
const dispatchForm = ref({ repairmanId: '' }) // 分派表单数据
const currentOrderId = ref('') // 当前操作的工单ID
const isDispatchLoading = ref(false) // 分派操作加载状态

// 加载待分派工单列表
const loadDispatchOrders = async () => {
  isLoading.value = true
  try {
    const res = await getWorkOrdersByStatus({ status: '待分派维修员' }) // 假设接口支持按状态筛选
    if (res.code === 200) {
      dispatchOrderList.value = res.data
    }
  } catch (err) {
    ElMessage.error('获取待分派工单失败', err)
  } finally {
    isLoading.value = false
  }
}

// 加载维修员列表
const loadRepairmen = async () => {
  try {
    const res = await getRepairmen() // 调用user.js中的获取维修员接口
    if (res.code === 200) {
      repairmanList.value = res.data // 假设返回格式为[{_id: 'xxx', name: '张三'}, ...]
    }
  } catch (err) {
    ElMessage.error('获取维修员列表失败', err)
  }
}

// 点击分派按钮
const handleDispatch = (row) => {
  currentOrderId.value = row._id // 假设工单数据包含_id字段
  dispatchForm.value.repairmanId = '' // 重置选择
  showDispatchDialog.value = true
  loadRepairmen() // 打开模态框时刷新维修员列表
}

// 确认分派
const confirmDispatch = async () => {
  if (!currentOrderId.value || !dispatchForm.value.repairmanId) return

  isDispatchLoading.value = true
  try {
    const res = await assignRepairmanByStation(currentOrderId.value, {
      repairman_id: dispatchForm.value.repairmanId,
    })
    if (res.code === 200) {
      ElMessage.success('维修员分派成功')
      showDispatchDialog.value = false
      loadDispatchOrders() // 刷新工单列表
    } else {
      ElMessage.error(res.message || '分派失败')
    }
  } catch (err) {
    ElMessage.error('网络请求失败', err)
  } finally {
    isDispatchLoading.value = false
  }
}

// 关闭模态框
const handleDialogClose = () => {
  showDispatchDialog.value = false
  currentOrderId.value = ''
}

// 组件挂载时加载数据
onMounted(() => {
  loadDispatchOrders()
})
</script>

<style scoped>
.workorder-dispatch-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.dialog-footer {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
